<template>
    <view class="container">
        <!-- 搜索栏 -->
        <view class="search-section">
            <SearchBox 
                v-model="searchValue" 
                placeholder="仓库名称或区域"
                @search="search"
                @input="input"
            />
        </view>

        <!-- 仓库列表 -->
        <view v-if="!loading && warehouseList.length" class="warehouse-list">
            <view v-for="(item, idx) in warehouseList" :key="item.id || idx" class="warehouse-card">
            <view class="vr-warehouse-card" @click="goDetail(item)">
                <image 
                    :src="item.thumbnailUrl || item.coverImage || '/static/assets/placeholder-warehouse.png'" 
                    class="vr-warehouse-img" 
                    mode="aspectFill"
                    @error="onImageError"
                ></image>
                <view class="vr-icon-center">
                    <view class="vr-icon-circle">
                        <image src="/static/assets/sourceInfo/source-icon-vrplay.png" class="vr-icon-image" mode="aspectFit"></image>
                    </view>
                </view>
                <view class="vr-warehouse-footer">
                    <text class="vr-warehouse-title">{{ item.warehouseName || ''}}</text>
                    <text class="vr-arrow">&#8250;</text>
                </view>
            </view>
            </view>
            <view v-if="hasMore" class="load-more" @click="loadMore">
                <uni-load-more :status="loadMoreStatus" :content-text="loadMoreText"></uni-load-more>
            </view>
        </view>

        <view v-else-if="!loading && !warehouseList.length" class="empty-state">
            <text class="empty-text">暂无相关仓库信息</text>
        </view>

        <!-- 通用选择弹窗 -->
        <uni-popup ref="selectorPopup" type="bottom" background-color="#fff">
            <view class="selector-popup">
                <view class="selector-popup__header">
                    <text class="selector-popup__title">{{ currentSelector.title }}</text>
                    <text class="selector-popup__close" @tap="closeSelector">关闭</text>
                </view>
                <scroll-view scroll-y style="max-height: 60vh;">
                    <view v-for="(opt, i) in currentSelector.options" :key="opt.value" class="selector-option"
                        :class="{ 'selector-option--active': opt.value === currentSelector.selectedValue }"
                        @tap="selectOption(opt)">
                        <text class="selector-option__label">{{ opt.label }}</text>
                        <text v-if="opt.value === currentSelector.selectedValue" class="selector-option__check">✓</text>
                    </view>
                </scroll-view>
            </view>
        </uni-popup>
    </view>
</template>

<script>
import WarehourseItem from '@/components/warehourseItem.vue';
import SearchBox from '@/components/SearchBox.vue';
import WarehouseCategoryRow from '@/components/WarehouseCategoryRow.vue';
import { API } from '@/utils/api.js';
import {
    getFullUrl,
    processWarehouseUrls,
    processNewsUrls
} from '@/utils/url-helper.js';
export default {
    components: {
        WarehourseItem,
        SearchBox,
        WarehouseCategoryRow
    },
    data() {
        return {
            searchValue: '',
            loading: false,
            // 接口数据
            parkList: [],
            parkAreaList: [],
            warehouseTypes: [],
            warehouseTags: [],
            warehouseList: [],
            // 分页
            page: 1,
            size: 10,
            hasMore: false,
            loadMoreStatus: 'more',
            loadMoreText: {
                contentdown: '上拉显示更多',
                contentrefresh: '正在加载...',
                contentnomore: '没有更多数据了'
            },
            // 选择器 & 筛选
            filters: {
                parkId: null,
                areaId: null,
                typeId: null,
                tagId: null,
                parkLabel: '',
                areaLabel: '',
                typeLabel: '',
                tagLabel: ''
            },
            currentSelector: {
                key: '',
                title: '',
                options: [],
                selectedValue: null
            }
        }
    },
    computed: {
        selectedTags() {
            const tags = [];
            if (this.filters.areaId) tags.push({ key: 'area', label: `区域：${this.filters.areaLabel}` });
            if (this.filters.parkId) tags.push({ key: 'park', label: `园区：${this.filters.parkLabel}` });
            if (this.filters.tagId) tags.push({ key: 'tag', label: `行业：${this.filters.tagLabel}` });
            if (this.filters.typeId) tags.push({ key: 'type', label: `库形：${this.filters.typeLabel}` });
            return tags;
        }
    },
    async onLoad() {
        try {
            await Promise.allSettled([
                this.loadParkList(),
                this.loadParkAreaList(),
                this.loadWarehouseTypes(),
                this.loadWarehouseTags()
            ]);
        } catch (e) {
            console.error('基础数据加载失败', e);
        } finally {
            await this.loadWarehouseList();
        }
    },
    // 添加分享功能
    onShareAppMessage() {
        return {
            title: 'VR看仓 - 360度全景仓库体验',
            path: '/pages/warehouse/AIwareHouse',
            imageUrl: '/static/assets/share/vr-warehouse-share.png'
        }
    },
    // 分享到朋友圈
    onShareTimeline() {
        return {
            title: 'VR看仓 - 360度全景仓库体验',
            imageUrl: '/static/assets/share/vr-warehouse-share.png'
        }
    },
    methods: {
        async loadParkList() {
         
            try {
                const res = await API.park.getList({});
                this.parkList = Array.isArray(res?.rows) ? res.rows : (Array.isArray(res) ? res : []);
            } catch (e) {
                console.error('获取园区列表失败', e);
            }
        },
        async loadParkAreaList() {
            try {
                const res = await API.park.getAreaList({});
                this.parkAreaList = Array.isArray(res?.rows) ? res.rows : (Array.isArray(res) ? res : []);
            } catch (e) {
                console.error('获取园区区域列表失败', e);
            }
        },
        async loadWarehouseTypes() {
            try {
                const res = await API.warehouse.getWarehouseTypes();
                this.warehouseTypes = Array.isArray(res?.rows) ? res.rows : (Array.isArray(res) ? res : []);
            } catch (e) {
                console.error('获取仓库类型失败', e);
            }
        },
        async loadWarehouseTags() {
            try {
                const res = await API.warehouse.getWarehouseTags();
                this.warehouseTags = Array.isArray(res?.rows) ? res.rows : (Array.isArray(res) ? res : []);
            } catch (e) {
                console.error('获取仓库标签失败', e);
            }
        },
        normalizeOptions(list, labelKeys = [], valueKeys = []) {
            if (!Array.isArray(list)) return [];
            const pickFirst = (obj, keys, fallback) => {
                for (let i = 0; i < keys.length; i += 1) {
                    const k = keys[i];
                    if (obj && obj[k] !== undefined && obj[k] !== null && obj[k] !== '') return obj[k];
                }
                return fallback;
            };
            return list.map((it, idx) => ({
                label: pickFirst(it, labelKeys.concat(['label', 'name', 'title', 'parkName', 'areaName', 'typeName', 'tagName']), `选项${idx + 1}`),
                value: pickFirst(it, valueKeys.concat(['id', 'value', 'code', 'key']), idx),
                raw: it
            }));
        },
        openSelector(key) {
            const config = {
                park: { title: '选择园区', list: this.parkList, labelKeys: ['parkName', 'name', 'label'], valueKeys: ['id', 'parkId', 'value'] },
                area: { title: '选择区域', list: this.parkAreaList, labelKeys: ['areaName', 'name', 'label'], valueKeys: ['id', 'areaId', 'value'] },
                type: { title: '选择库形', list: this.warehouseTypes, labelKeys: ['typeName', 'name', 'label'], valueKeys: ['id', 'typeId', 'value'] },
                tag: { title: '选择行业', list: this.warehouseTags, labelKeys: ['tagName', 'name', 'label'], valueKeys: ['id', 'tagId', 'value'] }
            };
            const c = config[key];
            if (!c) return;
            const options = this.normalizeOptions(c.list, c.labelKeys, c.valueKeys);
            const selectedValue = (
                key === 'park' ? this.filters.parkId :
                    key === 'area' ? this.filters.areaId :
                        key === 'type' ? this.filters.typeId :
                            key === 'tag' ? this.filters.tagId : null
            );
            this.currentSelector = { key, title: c.title, options, selectedValue };
            this.$refs.selectorPopup && this.$refs.selectorPopup.open();
        },
        closeSelector() {
            this.$refs.selectorPopup && this.$refs.selectorPopup.close();
        },
        selectOption(opt) {
            if (!opt) return;
            console.log("opt", opt)
            if (this.currentSelector.key === 'park') {
                this.filters.parkId = opt.value;
                this.filters.parkLabel = opt.label;
            }
            if (this.currentSelector.key === 'area') {
                this.filters.areaId = opt.value;
                this.filters.areaLabel = opt.label;
            }
            if (this.currentSelector.key === 'type') {
                this.filters.typeId = opt.value;
                this.filters.typeLabel = opt.label;
            }
            if (this.currentSelector.key === 'tag') {
                this.filters.tagId = opt.value;
                this.filters.tagLabel = opt.label;
            }
            this.currentSelector.selectedValue = opt.value;
            this.closeSelector();
            this.page = 1;
            this.loadWarehouseList();
        },
        removeFilter(key) {
            if (key === 'park') { this.filters.parkId = null; this.filters.parkLabel = ''; }
            if (key === 'area') { this.filters.areaId = null; this.filters.areaLabel = ''; }
            if (key === 'type') { this.filters.typeId = null; this.filters.typeLabel = ''; }
            if (key === 'tag') { this.filters.tagId = null; this.filters.tagLabel = ''; }
            this.page = 1;
            this.loadWarehouseList();
        },
        async loadWarehouseList() {
            try {
                this.loading = true;
                const params = {
                    page: this.page,
                    size: this.size,
                    isVr:1
                };
                if (this.searchValue) params.keyword = this.searchValue;
                if (this.filters.parkId) params.parkId = this.filters.parkId;
                if (this.filters.areaId) params.areaId = this.filters.areaId;
                if (this.filters.typeId) params.typeId = this.filters.typeId;
                if (this.filters.tagId) params.tagId = this.filters.tagId;
                const res = await API.warehouse.getList(params);
                if (res.code === 200) {
                    console.log(res.rows);
                    const warehouseData = res;
                    if (warehouseData.rows) {
                        this.warehouseList = processWarehouseUrls(warehouseData.rows);
                        this.warehouseList.forEach(item => {
                            if (item.vrLink && item.vrLink.length > 0) {
                                item.warehouseTags = [{
                                    tagName: 'VR看仓',
                                    tagImage: '/static/assets/home/home-icon-vr.png',
                                    tagId: -2
                                }, ...item.warehouseTags];
                            }
                            if (item.isRecommend) {
                                item.warehouseTags = [{
                                    tagName: '推荐',
                                    tagImage: '/static/assets/home/home-isRecommend.png',
                                    tagId: -1
                                }, ...item.warehouseTags];
                            }
                        });
                        this.hasMore = warehouseData.rows.length >= this.size;
                    } else {
                        this.warehouseList = [];
                        this.hasMore = false;
                    }
                } else {
                    this.warehouseList = [];
                    this.hasMore = false;
                }
            } catch (e) {
                console.error('获取仓库列表失败', e);
                this.warehouseList = [];
                this.hasMore = false;
            } finally {
                this.loading = false;
            }
        },
        search() {
            this.page = 1;
            this.loadWarehouseList();
        },
        input(value) {
            this.searchValue = value;
        },
        goReserve(item) {
            // 处理预约逻辑
            console.log('预约看仓:', item);
        },
        goContact(item) {
            // 处理联系客服逻辑
            console.log('联系客服:', item);
        },
        loadMore() {
            if (this.hasMore && !this.loading) {
                this.page++;
                this.loadWarehouseList();
            }
        },
        goDetail(item) {
            const id = item.id || item.warehouseId;
            if (!id) {
                uni.showToast({ title: '缺少仓库ID', icon: 'none' });
                return;
            }
            uni.navigateTo({ 
                url: '/pages/warehouse/warehouseDetail?id=' + encodeURIComponent(id) 
            });
        },
        onImageError(e) {
            console.error('图片加载失败:', e.detail.message);
            // 可以在这里设置一个默认图片
            e.target.src = '/static/assets/placeholder-warehouse.png';
        }
    }
}
</script>

<style lang="less" scoped>
.container {
    background: #f5f5f5;
    min-height: 100vh;
    padding-bottom: 120rpx;
}

.search-section {
    background: #ffffff;
    padding: 24rpx 24rpx 16rpx 24rpx;
    margin-bottom: 16rpx;
    box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
}

.warehouse-list {
    padding: 0 24rpx;
}

.warehouse-card {
    margin-bottom: 24rpx;
    background: #ffffff;
    border-radius: 16rpx;
    overflow: hidden;
    // box-shadow: 0 4rpx 16rpx rgba(0,0,0,0.08);
    transition: all 0.3s ease;
    
    // &:active {
    //     transform: scale(0.98);
    //     box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.12);
    // }
}

.load-more {
    padding: 40rpx 0;
    text-align: center;
}

.empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 120rpx 40rpx;
    min-height: 600rpx;
    background: #ffffff;
    margin: 24rpx;
    border-radius: 16rpx;
    box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);

    .empty-text {
        color: #999;
        font-size: 28rpx;
        margin-bottom: 30rpx;
    }
}

/* 选择弹窗样式 */
.selector-popup {
    padding: 24rpx 24rpx 12rpx 24rpx;
}

.selector-popup__header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-bottom: 12rpx;
    border-bottom: 1rpx solid #f0f0f0;
}

.selector-popup__title {
    font-size: 30rpx;
    font-weight: 600;
}

.selector-popup__close {
    font-size: 26rpx;
    color: #888;
}

.selector-option {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 24rpx 8rpx;
    border-bottom: 1rpx solid #f7f7f7;
}

.selector-option--active .selector-option__label {
    color: var(--primary-color);
    font-weight: 600;
}

.selector-option__label {
    font-size: 28rpx;
}

.selector-option__check {
    color: var(--primary-color);
    font-size: 28rpx;
}

/* VR仓库卡片样式 */
.vr-warehouse-card {
    position: relative;
    background: #ffffff;
    border-radius: 16rpx;
    overflow: hidden;
    box-shadow: 0 4rpx 16rpx  #3F3F3F;
    transition: all 0.3s ease;
    height: 400rpx;    
    &:active {
        transform: scale(0.98);
        box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.12);
    }
}

.vr-warehouse-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
}

.vr-icon-center {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 10;
}

.vr-icon-circle {
    border-radius: 50%;
    width: 80rpx;
    height: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
}

.vr-icon-image {
    width: 80rpx;
    height: 80rpx;
}

.vr-warehouse-footer {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 20rpx 24rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
    z-index: 5;
}

.vr-warehouse-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #ffffff;
    flex: 1;
    text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.8);
}

.vr-arrow {
    font-size: 36rpx;
    color: #ffffff;
    font-weight: bold;
    margin-left: 16rpx;
    text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.8);
}
</style>